<template>
  <vxe-grid :data="data" :columns="cols" :max-height="460" :min-height="52" class="w-full">
    <template #handle="{rowIndex}">
      <el-button link type="primary" @click="data.splice(rowIndex, 1)">删除</el-button>
    </template>
  </vxe-grid>
  <div class="border flex w-full px-3 py-2 border-t-0 dark:border-gray-700">
    <VSelect v-model="infoForm.id" :placeholder="'请输入'+(title || '')" :options="options.filter(d => !data.some(c => c.value === d[mainKey]))" filterable clearable class="w-60"
      @change="cardChange" />
    <el-button type="primary" plain class="ml-2" :disabled="!infoForm.id"
      @click="infoForm.id && data.push({ external_id: infoForm.item[mainKey], ...infoForm.item }) && (infoForm.id = '')">添加</el-button>
  </div>
</template>

<script lang="jsx" setup>
const props = defineProps({
  modelValue: { type: Object, default: () => ([]) },
  title: { type: String, default: () => '' },
  columns: { type: Array, default: () => ([]) },
  options: { type: Array, default: () => ([]) },
  mainKey: { type: String, default: '' },
})
const emit = defineEmits(['update:modelValue'])
const data = computed({
  get() {
    return props.modelValue
  },
  set(val) {
    emit('update:modelValue', val)
  }
})

const cols = computed(() => {
  return props.columns.map(d => {
    if(!d.slots) {
      d.slots = {
        default: ({row}) => <VText value={row[d.field]} line={d.line} />
      }
    }
    return d
  }).concat([{title: '操作', width: 100, slots: {default: 'handle'}}])
})

const infoForm = reactive({
  id: '',
  item: {}
})

const cardChange = ({option}) => {
  infoForm.item = option
}
</script>